﻿Imports System
Imports IDServer
Imports System.Threading.Thread
Imports System.IO
Imports System.String
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient

Public Class Frm_SelectSal
	Implements IDServer.IDServer.IDServer

	Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
	Private mDataset As DataSet
    Private FrmMain As New Frm_MainForm
	Public Fields, strFileName As String
    Private WithEvents MainFrom As New Frm_MainForm
    Private Captionstr As String = ""

    Private _Ds As DataSet '返回的資料集
    Private _fCode As String

    Private _ValidDate As String
    Private _Caption As String 'DataGridView 列名及標題
    Private _Resouce As String '源單據
    Private _MultiSelect As Boolean = True


    ''' <summary>
    ''' 生效日期
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property ValidDate() As String
        Get
            Return _ValidDate
        End Get
        Set(ByVal value As String)
            _ValidDate = value
        End Set
    End Property

    ''' <summary>
    ''' 獲取或設置資料集（DataSet）
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Ds() As DataSet
        Get
            Return _Ds
        End Get
        Set(ByVal value As DataSet)
            _Ds = value
        End Set
    End Property

    ''' <summary>
    ''' 獲取或設置查詢的代碼
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property fCode() As String
        Get
            Return _fCode
        End Get
        Set(ByVal value As String)
            _fCode = value
        End Set
    End Property

    ''' <summary>
    ''' 獲取或設置Caption
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Caption()
        Get
            Return _Caption
        End Get
        Set(ByVal value)
            _Caption = value
        End Set
    End Property

    ''' <summary>
    '''  獲取或設置Resouce：調用此單據的單據類型
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Resouce()
        Get
            Return _Resouce
        End Get
        Set(ByVal value)
            _Resouce = value
        End Set
    End Property

    Public Property MultiSelect()
        Get
            Return _MultiSelect
        End Get
        Set(ByVal value)
            _MultiSelect = value
        End Set
    End Property

    Private Sub Frm_SelectGoods_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        Try
            If e.KeyCode = Keys.Shift Then
                e.Handled = True
                If e.KeyCode = Keys.Enter Then
                    SendKeys.Send("+{TAB}")
                    SendKeys.Send("{F4}")
                End If
            Else
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        SendKeys.Send("{TAB}")
                End Select
            End If
        Catch ex As Exception
            MsgBox("txtCode_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub Frm_SelectSal_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Me.Cursor = Cursors.WaitCursor

            Captionstr = Me.Caption

            DataBindGridView(Me.dgrdGoods, Captionstr)
            DataBindGrid(Me.dgrdGoods, Captionstr)
            'BindGridCaption(Me.dgrdCustomer, BindHashTable(Captionstr))
            FormatDataGridView(Me.dgrdGoods)
            With Me.dgrdGoods
                .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
                .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
                .MultiSelect = True
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            End With

            If Me.txtfSaleOrdeNo.Text & "" <> "" Then
                Me.BtnFind_Click(sender, e)
            End If

            Me.txtfSaleOrdeNo.Focus()

            'listAllControl()

            If Me.Resouce = "SalInvoice" Then
                'Me.txtBarcode.Enabled = False
                Me.txtCode.Enabled = False
                Me.txtCnname.Enabled = False
                Me.txtEnname.Enabled = False
                Me.Label10.Text = "送货单号："


            End If

            Me.dgrdGoods.MultiSelect = Me.MultiSelect

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint

    End Sub

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd

    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave

    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function


    Private Sub txtBarcode_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtBarcode.KeyDown, txtCode.KeyDown, _
                                   txtCnname.KeyDown, txtEnname.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        Me.BtnFind_Click(sender, e)
                    Case Keys.Escape
                        Me.btnCancel_Click(sender, e)
                End Select
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub txtBarcode_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBarcode.TextChanged, txtCnname.TextChanged, _
               txtCode.TextChanged, txtEnname.TextChanged, txtfSaleOrdeNo.TextChanged, txtfWriteNo.TextChanged
        If Me.txtBarcode.Text.Length >= 7 Then
            Me.BtnFind_Click(sender, e)
        End If
    End Sub

    Private Sub BtnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFind.Click

        Try
            Dim Sql As String = ""
            Dim CurrentDate = ServerDate
            If Me.Dtpfrom.Value > Me.DTPto.Value Then
                MessageBox.Show("日期设置有误", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

            Select Case Me.Resouce
                Case "PurPO"

                    Sql = "select a.fcustomerid,a.fsaleordeno,a.fwriteno,b.fgoodsbarcode,"
                    Sql += "  c.code, c.cnname, c.enname, f.colorcode, g.sizecode, e.lista, c.purhaseprice, c.fMinpoqty,d.fFullname"
                    Sql += " into #SelectsaleordeNO1 from sal_saleordea a left join sal_saleordeb b on a.fsaleordeno=b.fsaleordeno"
                    Sql += " left join bsc_goods c on b.fgoodsbarcode=c.barcode"
                    Sql += " left join bsc_goodstype d  on c.goodstype=d.id"
                    Sql += " left join (SELECT c.itemcode,d.listcode,d.lista  FROM   bsc_otherdefinea c,bsc_otherdefineb d  WHERE  c.itemcode = 'UnitDefin' AND c.id = d.itemno)e on c.unit=e.listcode"
                    Sql += " left join bsc_colordefine f on c.color=f.colorcode"
                    Sql += " left join bsc_sizedefine g on  c.spec=g.sizecode where 1=1 and a.foperateDate between '" & FormatDate(Me.Dtpfrom.Text) & "' and '" & FormatDate(Me.DTPto.Text) & "'"

                    If Me.txtfSaleOrdeNo.TextLength > 0 Then
                        Sql += " and a.fsaleordeno like '%" & Me.txtfSaleOrdeNo.Text & "%'"
                    End If
                    If Me.txtfWriteNo.TextLength > 0 Then
                        Sql += " and a.fwriteno like '%" & Me.txtfWriteNo.Text & "%'"
                    End If
                    If Me.txtBarcode.TextLength > 0 Then
                        Sql += " and b.fgoodsbarcode like '%" & Me.txtBarcode.Text & "%'"
                    End If
                    If Me.txtCnname.TextLength > 0 Then
                        Sql += " and c.Cnname like '%" & Me.txtCnname.Text & "%'"
                    End If
                    If Me.txtEnname.TextLength > 0 Then
                        Sql += " and c.Enname like '%" & Me.txtEnname.Text & "%'"
                    End If
                    If Me.txtCode.TextLength > 0 Then
                        Sql += " and c.Code like '%" & Me.txtCode.Text & "%'"
                    End If

                    Sql += ";"

                    Sql += "select a.Num,a.Date,a.ValidDate,a.SuppCode,a.CurrencyID,Barcode=substring(b.barcode,2,len(rtrim(b.barcode))-2),b.Price into #SelectsaleordeNO2  FROM Pur_QuoteA a,Pur_QuoteB b  WHERE a.Billstatusid='B' and a.Num=b.Num   "
                    Sql += "and a.ValidDate<='" & CurrentDate & "'   and a.ValidDate =(select Max(c.ValidDate) FROM Pur_QuoteA c,Pur_QuoteB d WHERE d.Barcode=b.Barcode  and c.Suppcode=a.Suppcode              "
                    Sql += "and c.Num=d.Num GROUP BY c.SuppCode,d.Barcode) order by b.barcode;"
                    Sql += "select m.fCustomerid ,m.fsaleordeno ,m.fwriteno ,m.fgoodsbarcode as barcode,m.code,m.cnname,m.enname,m.colorcode as Color,m.sizecode as Spec,m.lista as Unit,m.fMinPoqty as POQty,m.ffullname as GoodsType,n.price from #SelectsaleordeNO1 m,#SelectsaleordeNO2 n where  replace(m.fgoodsbarcode,'*','')=n.barcode ;"
                    Sql += "drop table #SelectsaleordeNO1;"
                    Sql += "drop table #SelectsaleordeNO2;"

                Case "SalInvoice"
                    Sql = "select fSaleOrdeNo, fWriteNo, fDeliverMode, fDeliverDate," & _
                        "fcustomerType,fCustomerName, fLinkMan," & _
                        "fLinkPhone, fDeliverAddress, ShopNo, fEmployeeId, fSaleDate," & _
                        "fOrdeStatus, fDSIA, fBSI,FTAmount=fDSIA+fBSI, fPayMode, fRemark from V_SaleOrde WHERE fDeliverMode='到取' and fOrdeStatus='核准' "

                    If Me.txtfSaleOrdeNo.TextLength > 0 Then
                        Sql += " and fsaleordeno like '%" & Me.txtfSaleOrdeNo.Text & "%'"
                    End If

                    If Me.txtfWriteNo.TextLength > 0 Then
                        Sql += " and fwriteno like '%" & Me.txtfWriteNo.Text & "%'"
                    End If

                    Sql += " ORDER BY fSaleOrdeNo"

            End Select


            mDataset = ReturnDataset(Sql)

            Me.dgrdGoods.DataSource = mDataset.Tables(0)

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default

        End Try

    End Sub


    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Try
            If Me.dgrdGoods.SelectedRows.Count > 0 Then
                PubGoodsDataSet.Tables.Clear()

                Dim tb As New DataTable
                Dim FirstSelectRow, LastSelectRow, intSelectRows As Integer
                Dim intRows() As Integer

                '選擇的第1行

                FirstSelectRow = Me.dgrdGoods.SelectedRows(0).Index

                '選擇的最後一行

                If Me.dgrdGoods.SelectedRows.Count > 1 Then
                    LastSelectRow = Me.dgrdGoods.SelectedRows(Me.dgrdGoods.SelectedRows.Count - 1).Index

                End If


                intSelectRows = Me.dgrdGoods.SelectedRows.Count
                ReDim intRows(intSelectRows - 1)
                For i As Integer = 0 To intSelectRows - 1
                    intRows(i) = Me.dgrdGoods.SelectedRows(i).Index
                Next

                tb = mDataset.Tables(0).Copy
                tb.Rows.Clear()

                PubGoodsDataSet.Tables.Add(tb)

                '順向選擇
                If FirstSelectRow > LastSelectRow Then
                    For J As Integer = intRows.LongLength - 1 To 0 Step -1
                        'For Each row As DataGridViewRow In Me.dgrdGoods.Rows

                        Dim mRow As DataRow
                        mRow = tb.NewRow()

                        For Each col As DataColumn In tb.Columns
                            mRow(col) = Me.dgrdGoods.Rows(intRows(J)).Cells(col.ColumnName).Value
                        Next

                        tb.Rows.Add(mRow)
                        PubGoodsDataSet.AcceptChanges()

                        'Next

                    Next
                Else
                    '反向選擇
                    For J As Integer = 0 To intRows.LongLength - 1
                        'For Each row As DataGridViewRow In Me.dgrdGoods.Rows

                        Dim mRow As DataRow
                        mRow = tb.NewRow()

                        For Each col As DataColumn In tb.Columns
                            mRow(col) = Me.dgrdGoods.Rows(intRows(J)).Cells(col.ColumnName).Value
                        Next

                        tb.Rows.Add(mRow)
                        PubGoodsDataSet.AcceptChanges()

                    Next



                End If


                ''檢查選擇的銷售號是否為一個銷售單號
                'Dim IsOnly As Boolean = False
                'Dim fsaleordeno As String = ""
                'Dim strfsaleordeno As String = ""

                'If PubGoodsDataSet.Tables(0).Rows.Count > 1 Then
                '    fsaleordeno = PubGoodsDataSet.Tables(0).Rows(0).Item("fsaleordeno") & ""
                '    For I As Integer = 1 To PubGoodsDataSet.Tables(0).Rows.Count - 1
                '        strfsaleordeno = PubGoodsDataSet.Tables(0).Rows(I).Item("fsaleordeno") & ""
                '        If fsaleordeno <> strfsaleordeno Then
                '            MsgBox(GetMsg("PUR", "MSG003"), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                '            Exit Sub
                '        End If
                '    Next

                'End If


                Me.Ds = PubGoodsDataSet

            End If
            Me.Dispose()

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)



        End Try

    End Sub

	Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        'Me.Close()
        Me.Dispose()


    End Sub

    Private Sub dgrdGoods_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrdGoods.CellDoubleClick
        Me.btnOK_Click(sender, e)
    End Sub

  

    Private Sub dgrdGoods_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgrdGoods.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        Me.btnOK_Click(sender, e)
                    Case Keys.Escape
                        Me.btnCancel_Click(sender, e)
                End Select
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub dgrdGoods_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrdGoods.CellContentClick

    End Sub
End Class